import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/views/layout/index.vue'
import Home from '@/views/Home/index.vue'
import Article from '@/views/article/index.vue'
import Publish from '@/views/publish/index.vue'

import { getItem } from '@/utils/auth.js'

import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: () => import('../views/login/index.vue')
  },
  {
    path: '/',
    // alias: '/',  // 别名
    component: Layout,
    redirect: 'home',
    children: [
      {
        path: 'home',
        component: Home
      },
      {
        path: 'article',
        component: Article
      },
      {
        path: 'publish',
        component: Publish
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  Nprogress.start()
  if (getItem()) {
    to.path.toLowerCase() === 'login' ? next('/home') : next()
  } else {
    to.path.toLowerCase() === '/login' ? next() : next('/login')
  }
  Nprogress.done()
})

router.afterEach((to, from, next) => {
  Nprogress.done()
})

const originalPush = VueRouter.prototype.push

VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

export default router
